import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:toatool/src/utils/upgrade.dart';

import 'app_exceptions.dart';

class AppResponse {
  bool? _ok;
  dynamic _data;
  AppException? _error;

  bool get ok => _ok ?? false;
  dynamic get data => _data;
  AppException get error => _error ?? AppException();

  factory AppResponse.obtain(Response response) {
    // mock
    // response.data['code'] = 100;
    // response.data['msg'] = '模拟错误';

    try {
      var isHttpSuccess = response.statusCode! >= 200 &&
          response.statusCode! < 300 &&
          response.data != null;

      var code = response.data['code'] as int;

      if (isHttpSuccess && code == 1) {
        return AppResponse._success(response.data['data']);
      }

      if (isHttpSuccess && code == -1) {
        return AppResponse._failure(
            errorMsg: response.data['msg']?.toString() ?? 'エラーが発生しました');
      }

      if (isHttpSuccess && (code >= 300) && (code <= 304)) {
        return AppResponse._failure(
            errorMsg: response.data['msg']?.toString() ?? 'エラーが発生しました');
      }

      if (isHttpSuccess && code == 100 && (!kIsWeb)) {
        // app更新
        UpgradeUtil.upgarde(response);
        return AppResponse._failure(
            errorMsg:
                response.data['msg']?.toString() ?? 'アプリケーションはアップグレードが必要です');
      }

      return AppResponse._failureFromError(
          HttpException(response.statusMessage, response.statusCode));
    } catch (e) {
      return AppResponse._failure(errorMsg: e.toString());
    }
  }

  AppResponse._success(dynamic data) {
    _data = data;
    _ok = true;
  }

  AppResponse._failure({String? errorMsg}) {
    _error = AppException.obtainFromMessage(errorMsg);
  }

  AppResponse._failureFromError(AppException error) {
    _error = error;
  }
}
